package com.knife.easyexcel.read.validator.impl;

import com.knife.easyexcel.read.data.ImportDataWarp;
import com.knife.easyexcel.read.data.ImportValidatorContext;
import com.knife.easyexcel.read.validator.ImportValidator;
import org.apache.logging.log4j.util.Strings;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 添加字段Javax的校验，支持@NotNull等类似注解
 *
 * @author lth
 * @created 2025年07月16日 星期三 11:05
 */
public class DefaultValidator<T> implements ImportValidator<T> {
    private final Validator validator;

    public DefaultValidator() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    @Override
    public String validate(ImportDataWarp<T> cuxImportDataWarp, ImportValidatorContext<T> cuxImportValidatorContext) {
        T currData = cuxImportDataWarp.getData();
        Set<ConstraintViolation<T>> violations = validator.validate(currData);
        if (!violations.isEmpty()) {
            StringJoiner sj = new StringJoiner(",");
            for (ConstraintViolation<T> violation : violations) {
                sj.add(violation.getMessage());
            }
            return sj.toString();
        }
        return Strings.EMPTY;
    }

    @Override
    public Boolean fastFail() {
        return true;
    }
}